package com.cos.hospital.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;

import com.cos.hospital.R;
import com.cos.hospital.tool.UTxt;

import java.util.Timer;
import java.util.TimerTask;


/**
 * @Description: 倒计时按钮
 * @Author: Kosmos
 * @Date: 2017年4月25日 16:04
 * @Email: KosmoSakura@foxmail.com
 */
public class TimeButton extends android.support.v7.widget.AppCompatTextView {
    private final String textafter = "秒后重新获取";
    private final String textbefore = "获取验证码";
    private Timer t;
    private TimerTask tt;
    private int time;
    private boolean isRunning = false;
    private String state;

    public TimeButton(Context context) {
        super(context);
        this.setSingleLine();
        this.setTextColor(getResources().getColor(R.color.gray_txt));
    }

    public String getState() {
        return state;
    }

    /**
     * @param state 为空这可以用
     */
    public void setState(String state) {
        this.state = state;
        if (UTxt.isEmpty(state) && !isRunning) {
            this.setTextColor(getResources().getColor(R.color.green_txt));
        } else {
            this.setTextColor(getResources().getColor(R.color.gray_txt));
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public int getTime() {
        return time;
    }

    public TimeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setSingleLine();
    }

    @SuppressLint("HandlerLeak")
    Handler han = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (time < 1) {
                TimeButton.this.setText(textbefore);
                if (UTxt.isEmpty(state)) {
                    TimeButton.this.setTextColor(getResources().getColor(R.color.green_txt));
                } else {
                    TimeButton.this.setTextColor(getResources().getColor(R.color.gray_txt));
                }
                clearTimer();
                isRunning = false;
            } else {
                time--;
                TimeButton.this.setText(time + textafter);
                isRunning = true;
            }
        }

    };

    public void run(int max) {
        if (isRunning()) {
            return;
        }
        initTimer(max);
        this.setText(time + textafter);
        t.schedule(tt, 0, 1000);
    }

    private void initTimer(int max) {
        this.setTextColor(getResources().getColor(R.color.gray_txt));
        time = max;
        t = new Timer();
        tt = new TimerTask() {

            @Override
            public void run() {
                han.sendEmptyMessage(0x01);
            }
        };
    }


    private void clearTimer() {
        if (tt != null) {
            tt.cancel();
            tt = null;
        }
        if (t != null)
            t.cancel();
        t = null;
    }
}

